/* 类弹幕 */
class Barrage {
  
  // 弹幕行数
  count = 6
  // 颜色类
  colors = ['#00FFBB','#00BAFF','#D3C1FF']
  // 移动幅度
  step = 1
  
  constructor(el, data) {
    this.el = document.querySelector(el);
    this.width = this.el.clientWidth
    this.height = this.el.clientHeight
    this.lineHeight = this.height / this.count;
    console.log(this.width)
    this.marginRight = this.width / 2;
    
    let arr = Array.from({length: this.count}, () => []);
    data.forEach((item, index) => {
      arr[index % this.count].push(item)
    })
    this.data = arr.map((item, index) => {
      const content = []
      for (let i = 0; i < 8; i++) {
        content.push(...item);
      }
      return {
        content,
        top: this.lineHeight * index,
        left: 0,
      }
    })
    this.init()
  }
  
  init() {
    const singleWidth = this.width / this.data.length
    // console.log('data--->', this.data)
    this.data = this.data.map((item,index) => {
      const color = this.colors[index % 3]
      const htmlNode = document.createElement('div')
      htmlNode.className = 'item'
      htmlNode.style.top = `${item.top}px`
      htmlNode.style.left = `${item.left}px`
      htmlNode.style.color = color
      item.content.forEach((text, idx) => {
        let marginLeft = singleWidth;
        if (index === 0) {
          marginLeft = singleWidth;
        } else if (index === 1) {
          marginLeft = singleWidth * 3;
        } else if (index === 2) {
          marginLeft = singleWidth * 2;
        } else if (index === 3) {
          marginLeft = singleWidth * 4;
        } else if (index === 4) {
          marginLeft = singleWidth * 6;
        } else {
          marginLeft = singleWidth * 5;
        }
        htmlNode.innerHTML += `<span style="line-height:${this.lineHeight}px;padding-right:${this.marginRight}px;${idx === 0 ? `padding-left: ${marginLeft}px` : ''}">${text}</span>`
      })
      this.el.appendChild(htmlNode)
      return {
        ...item,
        html: htmlNode,
      }
    })
    this.data.forEach((item, index) => {
      this.loop(item.html, 0);
    })
  }
  
  loop(html, translateX) {
    requestAnimationFrame(() => {
      const max = html.clientWidth / 2;
      let x = translateX
      if (x >= max) {
        x = x - max
      } else {
        x += this.step
      }
      html.style.transform = `translateX(-${x}px)`
      this.loop(html, x)
    })
  }
  
}